package com.iteaj.iot.serial;

import com.fazecast.jSerialComm.SerialPortEvent;
import com.iteaj.iot.AbstractProtocol;

public class SerialEventProtocol extends AbstractProtocol<SerialMessage> {

    private Exception cause;
    private SerialPortEvent event;
    private SerialConnectProperties connectProperties;

    protected SerialEventProtocol(Object event, SerialConnectProperties connectProperties) {
        if(event instanceof SerialPortEvent) {
            this.event = (SerialPortEvent) event;
        } else {
            cause = (Exception) event;
        }
        this.connectProperties = connectProperties;
    }

    @Override
    public AbstractProtocol buildRequestMessage() {
        throw new UnsupportedOperationException("不支持的操作");
    }

    @Override
    public AbstractProtocol buildResponseMessage() {
        throw new UnsupportedOperationException("不支持的操作");
    }

    /**
     * 写数据到串口
     * @param msg
     * @return
     */
    public int write(byte[] msg) {
        return this.event.getSerialPort().writeBytes(msg, msg.length);
    }

    /**
     * 写数据到串口
     * @param msg
     * @param offset msg的写偏移量
     * @return
     */
    public int write(byte[] msg, int offset) {
        return this.event.getSerialPort().writeBytes(msg, msg.length - offset, offset);
    }

    @Override
    public SerialProtocolType protocolType() {
        return SerialProtocolType.Event;
    }

    public Exception getCause() {
        return cause;
    }

    public SerialPortEvent getEvent() {
        return event;
    }

    protected SerialEventProtocol setEvent(SerialPortEvent event) {
        this.event = event; return this;
    }

    public SerialConnectProperties getConnectProperties() {
        return connectProperties;
    }
}
